#coding=utf-8
'''
Created on 2017-7-15

@author: sandy
'''

from twisted.internet import task
import logging
import time
import Game
import HallBase
from pycommon import Const
import UserManager
import HallManager


class HallAutoPair(HallBase.HallBase):
    
    def __init__(self, hid, hc):
        HallBase.HallBase.__init__(self)
        self.usermap = {}
        self.tablemap = {}
        self.hid = hid
        self.hc = hc
        self.checkinterval = hc.get(u'checkinterval')
        self.level = hc.get(u'level')
        self.maxuser = hc.get(u'maxuser')
        self.matchNum = hc.get(u'matchNum')
        self.tabletype = hc.get(u'tabletype')
        self.times = 0
        self.looptime = 0
        
        
    def start(self):
        tablecount = self.maxuser / self.matchNum
        for i in range(tablecount):
            t = Game.instance.createTable(i, self.hc, self.tabletype)
            t.setHallId(self.hid)
            self.tablemap[i] = t
        l = task.LoopingCall(self.onTimer)
        l.start(self.checkinterval, False)
    
    def stop(self):
        pass
        
    def onTimer(self):
        self.times += 1
        begin = time.time()
        for t in self.tablemap.values():
            try:
                t.checkTable()
            except Exception:
                logging.exception("t.checkTable()")
        self.looptime += (time.time() - begin)
        if self.times == 1000:
            logging.info(u"looptime = %f", self.looptime/1000)
            self.times = 0
            self.looptime = 0

    
    def getTable(self,tableId):
        table = self.tablemap.get(tableId)
        return table
 
    def getId(self):
        return self.hid
    
    def getLevel(self):
        return self.level
    
    def getType(self):
        return u"AutoPair"
        
    def getParam(self, k):
        return self.hc.get(k)

    def getNewTalbe(self):
        for t in self.tablemap.values():
            if False == t.isEmptySeat():
                continue
            return t
        return None
    
    def userEnter(self, uid):
        full = self.isFull()
        if full:
            logging.warning("hallId=%d is full",self.hid)
            return Const.ERR_HALL_IS_FULL
        user = UserManager.instance.getUser(uid)
        if user.getHallId() != -1:
            logging.warn("HallAutoPair.userEnter() aready in hall uid=%d",uid)
            return Const.ERR_ALREADY_IN_HALL
        self.usermap[uid] = user
        user.setHallId(self.hid)
        return Const.ERR_OK
    
    def userLeave(self, uid, reason):
        user = UserManager.instance.getUser(uid)
        tableId = user.getTableId()
        table = self.getTable(tableId)
        if table:
            table.userLeave(uid, reason)
        else:
            logging.debug("uid=%d userLeave table isNone",uid)
        Game.instance.onUserLeaveHall(uid, self.hid, reason)
        self.usermap.pop(uid)

    def isFull(self):
        return len(self.usermap) >= self.maxuser
            
    def getHallInfo(self):
        d = {}
        d["id"] = self.hid
        d["matchNum"] = self.matchNum
        d['usetable'] = 0
        d['maxtable'] = len(self.tablemap.keys())
        return d
    
    def getFreeTalbe(self, user):
        for t in self.tablemap.values():
            if False == t.hasFreeSeat():
                continue
            return t
        return None

    def getFreeTalbeExcept(self, excepttable):
        for t in self.tablemap.values():
            if t.hasFreeSeat() and t != excepttable:
                return t
        return None
        
    def broadcastGameMsg(self, pkt):
        for t in self.tablemap.values():
            t.broadcast(pkt)
        
def create(hid, hc):
    logging.debug(u"create HallAutoPair() hid=%d", hid)
    ret = HallAutoPair(hid, hc)
    ret.start()
    return ret

if __name__ == '__main__':
    pass